package com.igd.order.service;

import java.sql.Timestamp;
import java.util.Date;

import org.springframework.stereotype.Service;

import com.igd.order.client.AccountClient;
import com.igd.order.dao.OrderDao;
import com.igd.order.dao.dto.OrderEntity;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderService {
	
    private final AccountClient accountClient;
    private final OrderDao orderDao;
    
    @GlobalTransactional(rollbackFor = Exception.class)
    public void createAccountOrder(Integer accountId, Long amount, boolean hasException) {
        System.out.println("xid:" + RootContext.getXID());
        // 1、远程扣减账户余额
        String result = accountClient.debit(accountId, amount);
        log.info("远程扣减库存结果:[{}]", result);
        
        // 2、下订单
        log.info("为账户accountId:[{}]创建订单.", accountId);
        OrderEntity order = new OrderEntity();
        order.setAccountId(accountId);
        order.setAmount(amount);
        order.setOrderTime(new Timestamp(new Date().getTime()));
        orderDao.insert(order);
        
        if (hasException) {
            throw new RuntimeException("发生了异常，分布式事物需要回滚");
        }
    }

}
